/**
 * 检查用户是否登录
 */
function checkLogin() {
    return localStorage.getItem('currentUser') !== null;
}

/**
 * 更新页面登录状态
 */
function updateAuthStatus() {
    const authLink = document.getElementById('authLink');
    const currentUser = JSON.parse(localStorage.getItem('currentUser'));
    
    if (authLink) {
        if (currentUser) {
            authLink.textContent = '退出登录';
            authLink.href = '#';
            authLink.onclick = function() {
                localStorage.removeItem('currentUser');
                window.location.reload();
            };
        } else {
            authLink.textContent = '登录/注册';
            authLink.href = 'login.html';
            authLink.onclick = null;
        }
    }
}

/**
 * 更新购物车数量显示
 */
function updateCartCount() {
    const cartCountElement = document.getElementById('cartCount');
    if (cartCountElement) {
        const cart = JSON.parse(localStorage.getItem('cart')) || [];
        const totalItems = cart.reduce((total, item) => total + item.quantity, 0);
        cartCountElement.textContent = totalItems;
    }
}

/**
 * 初始化页面
 */
function initPage() {
    updateAuthStatus();
    updateCartCount();
    
    // 如果用户未登录且不在登录/注册页，跳转到登录页
    if (!checkLogin() && !window.location.pathname.includes('login.html') && 
        !window.location.pathname.includes('register.html')) {
        window.location.href = 'login.html';
    }
}

/**
 * 表单验证 - 手机号
 */
function validatePhone(phone) {
    return /^1[3-9]\d{9}$/.test(phone);
}

/**
 * 表单验证 - 邮箱
 */
function validateEmail(email) {
    return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
}

/**
 * 显示错误消息
 */
function showError(elementId, message) {
    const element = document.getElementById(elementId);
    if (element) {
        element.textContent = message;
    }
}

/**
 * 清除错误消息
 */
function clearError(elementId) {
    const element = document.getElementById(elementId);
    if (element) {
        element.textContent = '';
    }
}

// 页面加载时初始化
document.addEventListener('DOMContentLoaded', initPage);

